package org.example.computerdesign.common;


import freemarker.template.Configuration;
import org.example.computerdesign.common.enums.MailTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
/**
 * @author 朱文权
 * */

@Service
public class SendEmail {
    @Autowired
    private JavaMailSender mailSender;
    @Autowired
    private Configuration freemarkerConfig;
    /**
     * 由谁发送邮件
     * */
    @Value("${spring.mail.username}")
    private String from;

    @Autowired
    private TemplateEngine templateEngine;
    /**
     * 发送普通的文本邮件
     * @param tos 接收者数组
     * @param subject 标题
     * @param content 内容
     */
    public void sendSimpleEmail(String[] tos, String subject, String content) {
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        simpleMailMessage.setFrom(from);
        simpleMailMessage.setTo(tos);
        simpleMailMessage.setSubject(subject);
        simpleMailMessage.setText(content);
        mailSender.send(simpleMailMessage);
    }
    /**
     * 发送普通的文本邮件
     * @param tos 接收者数组
     * @param subject 标题
     * @param context 模板填充内容
     * @param template 模板路径
     */
    public boolean sendHtmlMail(String[] tos, MailTemplate subject, Context context, String template) {
        try {
            String emailContent = templateEngine.process(template, context);
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(tos);
            helper.setSubject(subject.getTemplate());
            helper.setText(emailContent, true);
            mailSender.send(message);
        } catch (MessagingException e) {
            return false;
        }
        return true;
    }
}
